<script setup lang="ts">
import { ElTable, ElTableColumn, ElPagination, ElButton, vLoading, ElIcon, ElTooltip, ElSelectV2, ElInput, ElPopover, ElButtonGroup,ElSwitch } from "element-plus"
import Nifi from "../../nifi";
import { computed, reactive, ref, onMounted, h } from "vue";
import { chunk,get } from "lodash-es";
import ConfigFormEl from "./config.form.vue"
import DetailEl from "./detail.vue"


interface Props {
    nifi: Nifi
    uuid?: string
    id?: string
}
//
const emits = defineEmits<{ addGroup: [groupId: string, id: string] }>()
const props = defineProps<Props>();
const { nifi, uuid, id } = props;

//
const groupOptions = Object.keys(nifi.group.breadcrumb).map(id => ({ label: nifi.group.breadcrumb[id].name, value: id }))
const statusOption = ["DISABLED", "ENABLED", "VALIDATING", "DISABLING", "ENABLING"].map(n => ({ label: n, value: n }))
//
const eventTypeOptions = [
    "REPLAY",
    "DOWNLOAD",
    "CONTENT_MODIFIED",
    "DROP",
    "FORK",
    "CLONE",
    "RECEIVE",
    "ATTRIBUTES_MODIFIED",
    "CREATE"
]
//
const pages = reactive({ pageNum: 1, pageSize: 10, total: 0, sizes: [], layout: "prev, pager, next, total" })
let query = {}
const search = reactive({ eventType: new Array<string>(), componentName: "", componentType: "", fileSize: "", currentGroup: false,sort:"",sortBy:"" })
const clearSearch = () => {
    search.eventType = [];
    search.componentName = '';
    search.componentType = '';
    search.fileSize = '';
    search.currentGroup = false;
}
//
const status = ref<string[]>([])
const group = ref<string[]>([])
//
const list = reactive<any[]>([])
const fList = computed(() => {
    let l = list;
    if (l.length == 0) { return l }
    if (search.eventType?.length > 0) {
        l = l.filter(d => search.eventType?.includes(d.eventType));
    }
    if (search.componentName) {
        l = l.filter(d => d.componentName?.indexOf(search.componentName) > -1)
    }
    if (search.componentType) {
        l = l.filter(d => d.componentType?.indexOf(search.componentType) > -1)
    }
    if (search.currentGroup) {
        l = l.filter(d => d?.groupId == nifi.group.id)
    }
    if(search.sortBy && search.sort){
        l = l.sort((a,b) => {
            const av = get(a,search.sortBy) + ''
            const bv = get(b,search.sortBy) + ''
            const res = search.sort == 'ascending' ?  bv?.localeCompare(av) : av?.localeCompare(bv);
            // debugger;
            return res;
        })
    }
    pages.total = l.length;
    return l;
})
const tList = computed(() => {
    const l = fList.value;
    return chunk(l, pages.pageSize)
})
const data = computed(() => tList.value[pages.pageNum - 1] || [])
//
const loading = ref(false)
//
const refresh = async () => {
    loading.value = true;
    const res = await nifi.Provenance.getList(query)
    console.log('........',res)
    list.length = 0;
    list.push(...res.provenanceEvents)
    loading.value = false;
}

const initQuery = (q:any) => {
    query = q;
    refresh();
}

const handleQueryChange = (q:any) => {
    query = q;
}
//
const handleRefresh = () => { refresh() };

const handleAdd = () => { }

const handleReset = () => {
    clearSearch();
}

const handleConfig = (row: any) => { }
const handleGo = (row: any) => {
    emits('addGroup', row.parentGroupId, row.id)
}
// 启用控制器服务
const handleEnableCS = (row: any) => { }
// 启用控制器服务和引用服务
const handleEnableAll = (row: any) => { }
//
const handleDisable = (row: any) => { }

const handleDelete = (row: any) => { }
//
const handleSortChange = (args:any) => {
    const {prop,order} = args;
    search.sortBy = prop;
    search.sort = order;
}
//
const handleView = (row:any) => {
    nifi.box.dialog(() => h(DetailEl,{id:row.id,nifi}),{title:"数据溯源事件"})
}
// 下载
const handleDownload = (row:any) => {
    console.log('========>',row)
    const id = row.id;
    nifi.Provenance.downContent(id,'output')
}

</script>


<template>
    <div class="w-70vw h-70vh relative flex flex-col gap-8px">
        <!-- header -->
        <div class="h-40px flex items-center justify-between gap-10px">
            <div>
                    <el-button type="success" :loading="loading" @click="handleRefresh">刷新</el-button>
                    <ElPopover width="" placement="bottom-start" trigger="click" :teleported="false">
                        <template #reference>
                            <el-button type="success" :loading="loading" title="配置查询参数"><div class="i-uil:setting w-1em h-1em"></div></el-button>
                        </template>
                        <ConfigFormEl :id="id" :uuid="uuid" @init="initQuery" @change="handleQueryChange"></ConfigFormEl>
                    </ElPopover>
            </div>
            <div class="flex items-center gap-10px">
                <ElSelectV2 v-model="search.eventType" multiple collapse-tags :options="eventTypeOptions.map(s => ({label:s,value:s}))" placeholder="请选择事件类型"  class="min-w-140px" ></ElSelectV2>
                <ElInput v-model="search.componentName" placeholder="请输入组件名称" class="min-w-140px" ></ElInput>
                <ElInput v-model="search.componentType" placeholder="请输入组件类型" class="min-w-140px" ></ElInput>
                <ElSwitch v-model="search.currentGroup"  inline-prompt active-text="当前分组" inactive-text="全部分组"></ElSwitch>
                <ElButton @click="handleReset" :loading="loading">重置</ElButton>
            </div>
        </div>
        <div class="flex-1 overflow-hidden">
            <ElTable class="w-full important-h-full" v-loading="loading" :data="data" stripe highlight-current-row row-key="id" @sort-change="handleSortChange">
                <ElTableColumn label="序号" width="80" align="center" fixed >
                    <template #default="{ $index }">{{ pages.pageSize * (pages.pageNum - 1) + $index + 1 }}</template>
                </ElTableColumn>
                <ElTableColumn prop="eventTime" label="事件时间" sortable="custom" width="240" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn prop="eventType" label="事件类型" sortable="custom" width="120" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn prop="flowFileUuid" label="流文件UUID" sortable="custom" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn prop="fileSize" label="文件大小" sortable="custom" width="120" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn prop="componentName" label="组件名称" sortable="custom" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn prop="componentType" label="组件类型" sortable="custom" show-overflow-tooltip></ElTableColumn>
                <ElTableColumn width="140" label="操作" fixed="right">
                    <template #default="{ row }">
                        <ElButton title="查看" @click="() => handleView(row)" link type="primary"><div class="i-fluent-color:apps-list-detail-20"></div></ElButton>
                        <ElButton title="下载" @click="() => handleDownload(row)" link type="primary"><div class="i-line-md:download-loop"></div></ElButton>
                        <ElButton title="血缘" @click="() => handleDownload(row)" link type="primary"><div class="i-healthicons:blood-vessel-outline"></div></ElButton>
                    </template>
                    
                </ElTableColumn>
            </ElTable>
        </div>
        <div class="h-40px flex justify-end items-end">
            <ElPagination v-model:current-page="pages.pageNum" v-model:page-size="pages.pageSize" :total="pages.total"
                :page-sizes="pages.sizes" :layout="pages.layout"></ElPagination>
        </div>

    </div>
</template>